package com.ys.everydaynews.utils

import android.content.Context
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver
import android.widget.Toast
import java.util.regex.Matcher
import java.util.regex.Pattern

fun Any.toast(context: Context, duration: Int = Toast.LENGTH_SHORT): Toast {
    return Toast.makeText(context, this.toString(), duration).apply { show() }
}

object CommonUtils {


    /***
     * 手机号码检测
     */
    fun checkPhoneNum(num: String): Boolean {
        val regExp = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(14[5-9])|(166)|(19[8,9])|)\\d{8}$"
        val p = Pattern.compile(regExp)
        val m = p.matcher(num)
        return m.matches()
    }

    /**
     * 去空格回车
     * */
    fun replaceBlank(str: String): String {
        var dest = ""
        if (str != null) {
            val p = Pattern.compile("\\s*|\t|\r|\n")
            val m: Matcher = p.matcher(str)
            dest = m.replaceAll("")
        }
        return dest
    }

    /**
     * 输入框键盘跟随
     */
    fun getGlobalListener(
        decorView: View,
        contentView: View
    ): ViewTreeObserver.OnGlobalLayoutListener {
        return ViewTreeObserver.OnGlobalLayoutListener {
            val r = Rect()
            decorView.getWindowVisibleDisplayFrame(r)
            val height = decorView.context.resources.displayMetrics.heightPixels
            val diff = height - r.bottom
            if (diff != 0) {
                if (contentView.paddingBottom != diff) {
                    contentView.setPadding(0, 0, 0, diff)
                } else {
                    if (contentView.paddingBottom != 0) {
                        contentView.setPadding(0, 0, 0, 0)
                    }
                }
            }
        }
    }
}